package com.study.lock;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author wanghao
 * @version v1.0
 * @description: 集合线程不安全
 * @date 2021/12/27 11:13
 * @change [修改时间] [修改者]@[版本号] [修改内容说明]
 */
public class ThreadDemo4 {

    public static void main(String[] args) {
        // 创建ArrayList集合
//        List<String> list = new ArrayList<String>();

        // 解决方法
        // 1. Vector解决
//        List<String> list = new Vector<String>();

        // 2. Collections解决
//        List<String> list = Collections.synchronizedList(new ArrayList<String>());

        // 3. CopyOnWriteArrayList解决
        /*List<String> list = new CopyOnWriteArrayList<String>();

        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                // 向集合中添加数据
                list.add(UUID.randomUUID().toString().substring(0,8));
                // 从集合中获取数据
                System.out.println(list);
            },String.valueOf(i)).start();
        }*/

        // 演示HashSet
//        Set<String> set = new HashSet<String>();

        /*Set<String> set = new CopyOnWriteArraySet<>();

        for (int i = 0; i < 30; i++) {
            new Thread(()->{
                // 向集合中添加数据
                set.add(UUID.randomUUID().toString().substring(0,8));
                // 从集合中获取数据
                System.out.println(set);
            },String.valueOf(i)).start();
        }*/

        // 演示HashMap
//        Map<String,String> map = new HashMap<String, String>();

        Map<String,String> map = new ConcurrentHashMap<String, String>();
        for (int i = 0; i < 30; i++) {
            String key = String.valueOf(i);
            new Thread(()->{
                // 向集合中添加数据
                map.put(key,UUID.randomUUID().toString().substring(0,8));
                // 从集合中获取数据
                System.out.println(map);
            },String.valueOf(i)).start();
        }

    }

}
